package com.newshub.monitor.controller;

import com.newshub.common.Result;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import com.newshub.monitor.service.LogAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 日志分析控制器
 * 整合业务日志、异常日志和日志搜索功能
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor/logs")
@CrossOrigin(origins = "*")
public class LogAnalysisController {
    
    @Autowired
    private LogAnalysisService logAnalysisService;

    /**
     * 获取业务操作日志
     */
    @GetMapping("/business")
    @BusinessLog(module = "日志分析", description = "获取业务操作日志", level = LogLevel.INFO)
    public Result<Map<String, Object>> getBusinessLogs(
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        try {
            Map<String, Object> result = logAnalysisService.getBusinessLogs(module, username, operation, startTime, endTime, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取业务操作日志失败", e);
            return Result.error("获取业务操作日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取异常日志
     */
    @GetMapping("/exceptions")
    @BusinessLog(module = "日志分析", description = "获取异常日志", level = LogLevel.INFO)
    public Result<Map<String, Object>> getExceptionLogs(
            @RequestParam(required = false) String exceptionType,
            @RequestParam(required = false) String alertLevel,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        try {
            Map<String, Object> result = logAnalysisService.getExceptionLogs(exceptionType, alertLevel, startTime, endTime, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取异常日志失败", e);
            return Result.error("获取异常日志失败: " + e.getMessage());
        }
    }

    /**
     * 搜索日志
     */
    @PostMapping("/search")
    @BusinessLog(module = "日志分析", description = "搜索日志", level = LogLevel.INFO)
    public Result<Map<String, Object>> searchLogs(@RequestBody Map<String, Object> searchParams) {
        
        try {
            String keyword = (String) searchParams.get("keyword");
            String logLevel = (String) searchParams.get("logLevel");
            String module = (String) searchParams.get("module");
            LocalDateTime startTime = null;
            LocalDateTime endTime = null;
            Integer pageNum = (Integer) searchParams.getOrDefault("pageNum", 1);
            Integer pageSize = (Integer) searchParams.getOrDefault("pageSize", 50);
            
            // 处理时间参数
            if (searchParams.get("startTime") != null) {
                startTime = LocalDateTime.parse((String) searchParams.get("startTime"));
            }
            if (searchParams.get("endTime") != null) {
                endTime = LocalDateTime.parse((String) searchParams.get("endTime"));
            }
            
            Map<String, Object> result = logAnalysisService.searchLogs(keyword, logLevel, module, startTime, endTime, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索日志失败", e);
            return Result.error("搜索日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取实时日志
     */
    @GetMapping("/realtime")
    @BusinessLog(module = "日志分析", description = "获取实时日志", level = LogLevel.INFO)
    public Result<Map<String, Object>> getRealtimeLogs(
            @RequestParam(defaultValue = "100") Integer limit,
            @RequestParam(defaultValue = "false") Boolean follow) {
        
        try {
            Map<String, Object> result = logAnalysisService.getRealtimeLogs(limit, follow);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取实时日志失败", e);
            return Result.error("获取实时日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取日志统计信息
     */
    @GetMapping("/stats")
    @BusinessLog(module = "日志分析", description = "获取日志统计信息", level = LogLevel.INFO)
    public Result<Map<String, Object>> getLogStats(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        try {
            Map<String, Object> result = logAnalysisService.getLogStats(startTime, endTime);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取日志统计信息失败", e);
            return Result.error("获取日志统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户活动统计
     */
    @GetMapping("/user-activity")
    @BusinessLog(module = "日志分析", description = "获取用户活动统计", level = LogLevel.INFO)
    public Result<Map<String, Object>> getUserActivityStats(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "10") Integer limit) {
        
        try {
            Map<String, Object> result = logAnalysisService.getUserActivityStats(startTime, endTime, limit);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户活动统计失败", e);
            return Result.error("获取用户活动统计失败: " + e.getMessage());
        }
    }
}
